package com.zj.framework.okhttp;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * @author xi.yang(xi.yang@downjoy.com)
 * @create 2018-06-26 上午 10:18
 **/
public class OkHttpUtil {
    private static final Logger logger = LoggerFactory.getLogger(OkHttpUtil.class);
    public static String get(Map<String, String> headers, String url, Map<String, String> forms) {
        try {
            OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
            StringBuffer sb = new StringBuffer(url);
            if (null != forms) {
                sb.append("?");
                for (String key : forms.keySet()) {
                    sb.append(key).append("=").append(forms.get(key)).append("&");
                }
            }
            Request request = new Request.Builder().url(sb.toString()).headers(Headers.of(headers)).build();
            Response response = okHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
            logger.error("ok http client get error :{}", e.getMessage());
            e.printStackTrace();
        }
        return "get not success";
    }

    public static String post(Map<String, String> headers, String url, Map<String, String> forms) {
        try {
            OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
            FormBody.Builder formBody = new FormBody.Builder();
            if (forms != null) {
                for (String key : forms.keySet()) {
                    formBody.add(key, forms.get(key));
                }
            }
            Request request = new Request.Builder().url(url).headers(Headers.of(headers)).post(formBody.build()).build();
            Response response = okHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
            logger.error("ok http client post error :{}", e.getMessage());
            e.printStackTrace();
        }
        return "post not success";
    }
}
